package cn.bjxy.shishaolong.request_answer.controller;


import cn.bjxy.shishaolong.common.ResultMsg;
import cn.bjxy.shishaolong.common.StatusCode;
import cn.bjxy.shishaolong.common.SysConst;
import cn.bjxy.shishaolong.request_answer.entity.Adopte;
import cn.bjxy.shishaolong.request_answer.entity.Collect;
import cn.bjxy.shishaolong.request_answer.entity.Report;
import cn.bjxy.shishaolong.request_answer.entity.Request;
import cn.bjxy.shishaolong.request_answer.service.ICollectService;
import cn.bjxy.shishaolong.request_answer.service.IReportService;
import cn.bjxy.shishaolong.system.annotation.Permission;
import cn.bjxy.shishaolong.system.exception.OperatorFailureException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 时少龙
 * @since 2019-03-16
 */
@RestController
@CrossOrigin
@RequestMapping("/api/request_answer/request")
public class RequestController extends RequestAnswerBaseController {

    @Autowired
    private ICollectService collectService;
    @Autowired
    private IReportService reportService;

    private final static String REQUEST_ID_KEY = "requestId";

    /**
     * 按条件查询
     *
     * @param param
     * @return
     */
    @RequestMapping("/queryByCondition")
    public ResultMsg queryByCondition(@RequestBody JSONObject param) {
        try {
            //查询条件
            Request request = null;
            if (param.containsKey(SysConst.QUERY_CONDITION_KEY)) {
                request = param.getObject(SysConst.QUERY_CONDITION_KEY, Request.class);
            }
            //分页查询
            if (param.containsKey(SysConst.PAGA_CURRENT_KEY) && param.containsKey(SysConst.PAGA_SIZE_KEY)) {
                IPage<Request> page = new Page<>();
                page.setCurrent(param.getLong(SysConst.PAGA_CURRENT_KEY)).setSize(param.getLong(SysConst.PAGA_SIZE_KEY));
                IPage<Request> list = requestService.queryByCondition(page, request);
                return ResultMsg.success(list);
            } else {  //普通查询
                requestService.queryByCondition(request);
                return ResultMsg.success(request);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.QUERY_FAILURE, StatusCode.QUERY_FAILURE_MSG);
        }
    }

    /**
     * 查询问题详情及回答
     *
     * @return
     */
    @PostMapping("/queryRequestAnswerById")
    public ResultMsg queryRequestAnswerById(@NotNull @RequestBody JSONObject param) {
        try {
            if (!param.containsKey(REQUEST_ID_KEY)) {
                return ResultMsg.create(StatusCode.PARAMETER_ERROR, StatusCode.PARAMETER_ERROR_MSG);
            }
            Integer requestId = param.getInteger(REQUEST_ID_KEY);
            Request request = requestService.queryRequestAnswerById(requestId);
            return ResultMsg.success(request);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.QUERY_FAILURE, StatusCode.QUERY_FAILURE_MSG);
        }
    }

    /**
     * 保存
     *
     * @param myRequest
     * @return
     */
    @PostMapping("/save")
    @Permission
    public ResultMsg save(HttpServletRequest request, @RequestBody Request myRequest) {
        try {
            if (myRequest == null) {
                return ResultMsg.create(StatusCode.PARAMETER_ERROR, StatusCode.PARAMETER_ERROR_MSG);
            }
            // 给修改日期赋值
            Integer currentUserId = getCurrentUserId(request);
            myRequest.setUpdateAt(LocalDateTime.now()).setUserId(currentUserId);
            requestService.saveOrUpdate(myRequest);
            return ResultMsg.success();
        } catch (OperatorFailureException ofe) {
            ofe.printStackTrace();
            return ResultMsg.create(ofe.getCode(), ofe.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.SAVE_FAILURE, StatusCode.SAVE_FAILURE_MSG);
        }
    }

    /**
     * 收藏问答
     *
     * @param collect
     * @return
     */
    @RequestMapping("/collecte")
    @Permission
    public ResultMsg collecte(HttpServletRequest httRequest, @RequestBody Collect collect) {
        try {
            if (collect == null) {
                return ResultMsg.create(StatusCode.PARAMETER_ERROR, StatusCode.PARAMETER_ERROR_MSG);
            }
            // 获取当前用户
            collect.setUserId(getCurrentUserId(httRequest));
            // 如果查出相同的，拦截掉，不让修改
            Collect retCollection = collectService.getOne(new QueryWrapper<Collect>().lambda()
                    .eq(Collect::getReqAnsId, collect.getReqAnsId())
                    .eq(Collect::getReqAnsType, collect.getReqAnsType())
                    .eq(Collect::getUserId, collect.getUserId()));

            if (retCollection != null) return ResultMsg.create(StatusCode.DATA_EXIST, StatusCode.DATA_EXIST_MSG);
            collectService.save(collect);
            return ResultMsg.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.SAVE_FAILURE, StatusCode.SAVE_FAILURE_MSG);
        }
    }

    /**
     * 举报问答
     *
     * @param report
     * @return
     */
    @RequestMapping("/report")
    @Permission
    public ResultMsg report(HttpServletRequest httRequest, @RequestBody Report report) {
        try {
            if (report == null) {
                return ResultMsg.create(StatusCode.PARAMETER_ERROR, StatusCode.PARAMETER_ERROR_MSG);
            }
            report.setUserId(getCurrentUserId(httRequest));
            // 如果查出相同的，拦截掉，不让修改
            Report retReport = reportService.getOne(new QueryWrapper<Report>().lambda()
                    .eq(Report::getReqAnsId, report.getReqAnsId())
                    .eq(Report::getReqAnsType, report.getReqAnsType()));
            if (retReport != null) return ResultMsg.create(StatusCode.DATA_EXIST, StatusCode.DATA_EXIST_MSG);
            reportService.save(report);
            return ResultMsg.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.SAVE_FAILURE, StatusCode.SAVE_FAILURE_MSG);
        }
    }

    @RequestMapping("/adopt")
    @Permission
    public ResultMsg adopt(HttpServletRequest httRequest, @RequestBody Adopte adopte) {
        try {
            if (adopte == null) {
                return ResultMsg.create(StatusCode.PARAMETER_ERROR, StatusCode.PARAMETER_ERROR_MSG);
            }

            adopte.setUserId(getCurrentUserId(httRequest));
            // 如果查出相同的，拦截掉，不让修改
            Request retRequest = isRequestorOwn(adopte.getUserId(), adopte.getRequestId());
            if (!Objects.isNull(retRequest))
                return ResultMsg.create(StatusCode.ILLEGAL_OPERATION, StatusCode.ILLEGAL_OPERATION_MESSAGE);
            retRequest = new Request();
            retRequest.setUpdateAt(LocalDateTime.now()).setBestAnswerId(adopte.getAnswerId());
            // 保存采纳的值
            requestService.update(retRequest,
                    new UpdateWrapper<Request>().lambda().eq(Request::getTid, adopte.getRequestId()));
            return ResultMsg.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.SAVE_FAILURE, StatusCode.SAVE_FAILURE_MSG);
        }
    }

    /**
     * 删除
     *
     * @param param
     * @return
     */
    @DeleteMapping("/delete")
    @Permission
    public ResultMsg delete(HttpServletRequest httRequest, @RequestBody JSONObject param) {
        try {
            if (param == null || !param.containsKey(SysConst.ID) || param.getString(SysConst.ID).isEmpty()) {
                return ResultMsg.create(StatusCode.PARAMETER_ERROR, StatusCode.PARAMETER_ERROR_MSG);
            }
            String id = param.getString(SysConst.ID);
            Integer userId = getCurrentUserId(httRequest);
            Request myRequet = isRequestorOwn(userId, Integer.parseInt(id));
            if (Objects.isNull(myRequet)) { // 没找到，说明没有此问题
                return ResultMsg.create(StatusCode.ILLEGAL_OPERATION, "未查找到问题，或者" + StatusCode.ILLEGAL_OPERATION_MESSAGE);
            }
            // 删除
            requestService.update(new Request().setUpdateAt(LocalDateTime.now()).setDeletedAt(LocalDateTime.now()),
                    new UpdateWrapper<Request>().lambda().eq(Request::getTid, id).eq(Request::getUserId, userId));
            return ResultMsg.success();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.create(StatusCode.DELETE_FAILUER, StatusCode.DELETE_FAILUER_MSG);
        }
    }
}
